JQUERY VAL()

Vignesh S



jQuery val()

The jQuery val() method is used to get or set the value of form elements such as <input>, <select>, and <textarea>.

Syntax 

  1. To get value: var value = $("selector").val();
  2. To set value: $("selector").val("new value");
  3. To set value using function: $(selector).val(function(index,currentvalue));
Parameter details 
  • Value (Required):Specifies the value to be assigned to the attribute.
  • Function (index, currentValue) (Optional):A function that returns the value to be set.
  • index: The position of the element in the set.
  • currentValue: The current value of the element.
Example 
To get value:
<!DOCTYPE html>
<html>
<body>
  <input type="text" id="myInput" value="Hello World">
  <script>
var inputValue = $("#myInput").val();
console.log(inputValue); // Output: "Hello World"
  </script>
</body>
</html>

To set value:
<!DOCTYPE html>
<html>
<body>
  <form id="myForm">
  <label for="name">Name:</label>
  <input type="text" id="name" value="Vignesh">
  <br>
  <label for="email">Email:</label>
  <input type="email" id="email" value="vigneshs@gmail.com">
  <br>
  <label for="role">Role:</label>
  <select id="role">
    <option value="1">User</option>
    <option value="2">Admin</option>
    <option value="3">Moderator</option>
  </select>
 <br>
<br>
  <button type="button" id="updateButton">Update Values</button>
</form>
   <script>
// jQuery code
$("#updateButton").click(function() {
  // Set the value of the "name" input field
  $("#name").val("Jane Smith");
  // Set the value of the "email" input field
 $("#email").val("jane@example.com");
  // Set the selected value of the dropdown to "Moderator"
  $("#role").val("3");
});
 </script>
</body>
</html>
Tags
Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send